const Subscription = require('egg').Subscription;

class ScanTasks extends Subscription {
  // 每30秒执行一次
  static get schedule() {
    return {
      interval: '30s',
      type: 'worker',
    };
  }

  async subscribe() {
    const { ctx } = this;
    const now = new Date();    
    const startTime = new Date(now.getTime() - 30000 + 8 * 60 * 60 * 1000); // 提前30秒开始扫描
    const endTime = new Date(now.getTime() + 30000 + 8 * 60 * 60 * 1000); // 包含未来30秒的任务

    const tasks = await ctx.model.Phonedb.find({
      triggerTime: { $gte: startTime, $lte: endTime },
      isok: false,
      istask: true,
    }).limit(100);
    
    if (tasks.length === 0){
      ctx.logger.info("该时间段没有加好友任务");
    }

    for (const task of tasks) {
      try {
        const result = await ctx.service.wxfriend.addFriendByV3(
          task.ownerWxid,
          task.v3,
          task.content,
        );
    
        if (result.code === 200) {
          await ctx.model.Phonedb.updateOne(
            { _id: task._id },
            {
              $set: { isok: true },
              $inc: { submitnum: 1 },
              $push: {
                logs: {
                  wxid: result.wxid,
                  nick: task.nick,
                  content: task.content,
                  msg: result.msg,
                  timeStamp: result.timestamp,
                },
              },
            }
          );
          console.log('✅ 打招呼成功:', {
            taskId: task._id,
            wxid: result.wxid,
          });
        } else {
          ctx.logger.error('❌ 打招呼失败:', result.msg);
        }
      } catch (error) {
        ctx.logger.error(`❌ 处理任务 ${task._id} 出现异常:`, error);
      }
    }
  }
}

module.exports = ScanTasks;
